package com.nuoniu.sibanyun.service.erp.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nuoniu.sibanyun.common.exception.NuoNiuException;
import com.nuoniu.sibanyun.common.lang.DateUtils;
import com.nuoniu.sibanyun.common.lang.StringUtils;
import com.nuoniu.sibanyun.entity.dto.ErpNumberSetSearchDto;
import com.nuoniu.sibanyun.entity.erp.ErpNumberSet;
import com.nuoniu.sibanyun.entity.erp.ErpProject;
import com.nuoniu.sibanyun.entity.vo.SimpleErpNumberSetVo;
import com.nuoniu.sibanyun.mapper.erp.ErpNumberSetMapper;
import com.nuoniu.sibanyun.service.erp.IErpAccountService;
import com.nuoniu.sibanyun.service.erp.IErpNumberSetService;
import com.nuoniu.sibanyun.userThread.UserInfo;
import com.nuoniu.sibanyun.userThread.UserThreadLocal;
import io.swagger.annotations.ApiModel;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 编号设置  服务实现类
 * </p>
 *
 * @author baiqiang
 * @since 2020-11-02
 */
@Service
public class ErpNumberSetServiceImpl extends ServiceImpl<ErpNumberSetMapper, ErpNumberSet> implements IErpNumberSetService {

    @Autowired
    private IErpAccountService accountService;
    @Autowired
    private IErpAccountService erpAccountService;

    @Override
    public void initData(UserInfo userInfo, Integer accountId) {
        List<ErpNumberSet> defErpNumberSets = this.liseDefErpNumberSet();
        if(defErpNumberSets.size() > 0){
            defErpNumberSets.forEach(item->{
                item.setAccountId(accountId);
                item.setCompanyId(userInfo.getCompanyId());
                item.setCreateUserId(userInfo.getUserId());
                item.setUpdateUserId(userInfo.getUserId());
                item.setId(null);
            });
            saveBatch(defErpNumberSets);
        }
    }

    @Override
    public List<ErpNumberSet> liseDefErpNumberSet() {
        QueryWrapper<ErpNumberSet> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("company_id", 1);
        queryWrapper.eq("account_id", 0);
        queryWrapper.ne("module_code", "CRM");
        List<ErpNumberSet> list = list(queryWrapper);
        return list;
    }

    @Override
    public Page<ErpNumberSet> pageList(Page pages, ErpNumberSet numberSet) {
        pages.setSize(-1);
        UserInfo userInfo = UserThreadLocal.get();
        QueryWrapper<ErpNumberSet> queryWrapper = new QueryWrapper<>();
        if(numberSet.getModuleCode() != null && !numberSet.getModuleCode().equals("CRM") && !numberSet.getModuleCode().equals("CM")) {
            Integer currentAccountId = accountService.getCurrentAccountId();
            if(null == currentAccountId) {
                throw new NuoNiuException(5001,"请创建账套");
            }
            queryWrapper.eq("account_id", currentAccountId);
        }
        queryWrapper.eq("company_id", userInfo.getCompanyId());
        queryWrapper.eq("status", 0);
        if(numberSet.getModuleCode() != null) {
            queryWrapper.eq("module_code", numberSet.getModuleCode());
        }
        return  page(pages, queryWrapper);
    }

    @Override
    public List<SimpleErpNumberSetVo> listErpNumberSet(ErpNumberSetSearchDto erpNumberSetSearchDto) {
        UserInfo userInfo = UserThreadLocal.get();
        Integer currentAccountId = accountService.getCurrentAccountId();
        List<SimpleErpNumberSetVo> mapList = baseMapper.listErpNumberSet(userInfo.getCompanyId(), currentAccountId,erpNumberSetSearchDto);
        return mapList;
    }

    @Override
    public List<SimpleErpNumberSetVo> listErpNumberParentList(String moduleCode) {
        UserInfo userInfo = UserThreadLocal.get();
        Integer currentAccountId = accountService.getCurrentAccountId();
        List<SimpleErpNumberSetVo> mapList = baseMapper.listErpNumberParentList(userInfo.getCompanyId(), currentAccountId, moduleCode);
        return mapList;
    }

    @Override
    public String getCode(ErpNumberSet numberSet, String code) {
        if(numberSet != null) {
            Integer streamNumber = numberSet.getStreamNumber() == null || numberSet.getStreamNumber() < 1 ? 4 : numberSet.getStreamNumber();
            if(numberSet.getIsSplitMark() == null) {
                numberSet.setIsSplitMark(false);
            }

            Integer startValue = numberSet.getStartValue() == null || numberSet.getStartValue() < 1 ? 1 : numberSet.getStartValue();
            String date = numberSet.getMedian() == 1 ? DateUtils.formatDate(new Date(), "yyyyMMdd") : DateUtils.formatDate(new Date(), "yyyyMM");
            if(StringUtils.isBlank(code)) {
                String streamNumberStr = String.format("%0"+streamNumber+"d", startValue); //自动补零
                if(numberSet.getIsSplitMark()) {
                    return numberSet.getCurrentCode() + "-" + date + "-" + streamNumberStr;
                }else {
                    return numberSet.getCurrentCode() + date + streamNumberStr;
                }
            }else {
                Integer codeLength = code.length();
                String num = Integer.parseInt(code.substring(codeLength - streamNumber, codeLength)) + 1 + "";
                String codeValue = "";
                if(num.length() > streamNumber) {
                    return null;
                }

                for(int i=0; i<streamNumber - num.length(); i++) {
                    codeValue += "0";
                }

                if(numberSet.getIsSplitMark()) {
                    return numberSet.getCurrentCode() + "-" + date + "-" + codeValue + num;
                }else {
                    return numberSet.getCurrentCode() + date + codeValue + num;
                }
            }
        }
        return null;
    }

    @Override
    public ErpNumberSet getByCode(String codeType) {
        UserInfo userInfo = UserThreadLocal.get();
        Integer currentAccountId = accountService.getCurrentAccountId();
        ErpNumberSet numberSet = baseMapper.getByCode(codeType, userInfo.getCompanyId(), currentAccountId);
        return numberSet;
    }

    @Override
    public void saveNumberSet(ErpNumberSet numberSet) {
        UserInfo userInfo = UserThreadLocal.get();
        if(numberSet.getId() == null) {
            if(numberSet.getModuleCode() != null && !numberSet.getModuleCode().equals("CRM")) {
                Integer accountId = erpAccountService.getCurrentAccountId();
                if(accountId == null) {
                    throw new NuoNiuException(5001,"请先创建账套");
                }
                numberSet.setAccountId(accountId);
            }

            numberSet.setCompanyId(userInfo.getCompanyId());
            numberSet.setCreateUserId(userInfo.getUserId());
        }else {
            numberSet.setUpdateUserId(userInfo.getUserId());
        }

        this.saveOrUpdate(numberSet);
    }

    @Override
    public void deleteById(Long id) {
        ErpNumberSet numberSet = this.getById(id);
        if(numberSet.getModuleCode().equals("CM")) {
            this.removeById(id);
        }
    }

    @Override
    public ErpNumberSet getByCode(String codeTyp, Integer companyId, Integer currentAccountId) {
        return baseMapper.getByCode(codeTyp, companyId, currentAccountId);
    }
}
